package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.Semaphore;

/**
 * Semaphore 示例
 */
public class _06_Semaphore {

    public static class SemaphoreDemo {

        private int count;

        final Semaphore semaphore = new Semaphore(1);

        public void addOne() {
            try {
                semaphore.acquire();
                count += 1;
            } catch (InterruptedException e) {
                //
            } finally {
                semaphore.release();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        final SemaphoreDemo demo = new SemaphoreDemo();

        Thread t1 = new Thread(demo::addOne, "t1");
        Thread t2 = new Thread(demo::addOne, "t2");
        Thread t3 = new Thread(demo::addOne, "t3");

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println(demo.count);
    }

}
